import { useEffect, useState } from 'react'
import style from './index.module.scss'
import { Modal, Form, Input, Button, message, InputNumber  } from "antd"
import { ShowEditProductFnc, EditProductFnc } from '@/api/goods'
import { itemType } from './type'
import PropTypes from 'prop-types'

const EditGoods = ({editBox, changeEditBox, goodsID, init, ipt, pageNow, pageSize}: any) => {
 const [form] = Form.useForm()
 // 用于做比较的form
 const [formObj, setFormObj] = useState({})
 
 // 打开编辑盒子
 const initFnc = async () => {
   if(goodsID !== undefined && goodsID !== '') {
    const res = await ShowEditProductFnc(goodsID)
    if(res.data.meta.status === 200) {
      form.setFieldsValue({
        goods_name: res.data.data.goods_name,
        goods_price: res.data.data.goods_price,
        goods_number: res.data.data.goods_number,
        goods_weight: res.data.data.goods_weight
      })
      setFormObj(form.getFieldsValue())
    }
   }
 }

 useEffect(() => { initFnc() }, [goodsID])

 // 提交修改数据
 const onFinish = async (values: itemType) => {
   if(JSON.stringify(formObj) === JSON.stringify(values)) {
    changeEditBox(false)
   } else {
    const res =  await EditProductFnc(goodsID,values)
    if(res.data.meta.status === 200) {
      message.success('更新成功', 1.5, () => {
        changeEditBox(false)
        init(ipt, pageNow, pageSize)
      })
    }
   }
 }
 return (
    <Modal title='修改商品' open={editBox} footer={null} onCancel={() => changeEditBox(false)}>
       <Form form={form} className={style.form} onFinish={onFinish} labelCol={{ span: 4 }}>
          <Form.Item name="goods_name" label="商品名称" rules={[{ required: true, message: '请输入商品名称' }, {min: 3, max: 100, message: '长度在3-100个字符'}]}>
            <Input/>
          </Form.Item>
            
          <Form.Item name="goods_price" label="商品价格" rules={[{ required: true, message: '请输入价格' }]}>
            <InputNumber style={{ width: '100%' }}/>
          </Form.Item>

          <Form.Item name="goods_number" label="商品数量" rules={[{ required: true, message: '请输入数量' }]}>
            <InputNumber style={{ width: '100%' }}/>
          </Form.Item>

          <Form.Item name="goods_weight" label="商品重量" rules={[{ required: true, message: '请输入重量' }]}>
            <InputNumber style={{ width: '100%' }}/>
          </Form.Item>

          <Form.Item style={{marginBottom: 0}}>
            <div className={style.btn}>
              <Button type="default" onClick={() =>changeEditBox(false)}>取消</Button>
              <Button type="primary" htmlType="submit">修改</Button>
            </div>
          </Form.Item>
        </Form>
    </Modal>
 )
}

export default EditGoods

EditGoods.proTypes = {
  editBox: PropTypes.bool.isRequired,
  changeEditBox: PropTypes.func.isRequired,
  goodsID: PropTypes.number.isRequired,
  init: PropTypes.func.isRequired,
  ipt: PropTypes.string.isRequired,
  pageNow: PropTypes.number.isRequired,
  pageSize: PropTypes.number.isRequired
}